{% extends 'admin/base.html' %}

{% block content %}
    <div class="w-full px-6 py-8">
        <div class="mb-6 flex justify-between items-center">
            <h1 class="text-2xl font-semibold">用户管理</h1>
            <div class="flex items-center space-x-4">
                <button onclick="showModal('add')"
                        class="px-4 py-2 bg-primary text-white hover:bg-primary/90 !rounded-button whitespace-nowrap">
                    <i class="fas fa-plus mr-2"></i>添加用户
                </button>
            </div>
        </div>

        <div class="bg-white !rounded-lg shadow">
            <table class="w-full">
                <thead>
                <tr class="text-left border-b border-gray-200">
                    <th class="px-6 py-4 text-sm font-medium text-gray-500">#</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">姓名</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">邮箱</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">管理员</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">创建时间</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">更新时间</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">操作</th>
                </tr>
                </thead>
                <tbody>
                {% for user_data in pagination.current_items %}
                    <tr class="border-b border-gray-200">
                        <td class="px-6 py-4">{{ loop.index }}</td>
                        <td class="px-6 py-4 text-center" style="color: #4e7fc7">{{ user_data.username }}</td>
                        <td class="px-6 py-4 text-center">{{ user_data.email }}</td>
                        <td class="px-6 py-4 text-center">{{ user_data.is_admin }}</td>
                        <td class="px-6 py-4 text-center">{{ user_data.created_at }}</td>
                        <td class="px-6 py-4 text-center">{{ user_data.updated_at }}</td>
                        <td class="px-6 py-4 text-center">
                            <button onclick="showModal('edit', '{{ user_data.id }}', '{{ user_data.username }}', '{{ user_data.email }}','{{ 'admin' if user_data.is_admin == '是' else 'user' }}')"
                                    class="p-2 text-primary hover:bg-primary/10 !rounded-button">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="delete_user('{{ user_data.id }}')"
                                    class="p-2 text-red-500 hover:bg-red-50 !rounded-button">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
            {% with endpoint='admin.manage_users', url_params={} %}
                {% include 'admin/components/page.html' with context %}
            {% endwith %}
        </div>
    </div>

    <div id="userModal" class="user-modal">
        <div class="user-modal-content">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-semibold" id="modalTitle">添加用户</h3>
                <button onclick="hideModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="userForm">
                <input type="hidden" id="userId">
                <div class="space-y-4">
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                        <input id="username" name="username" type="text"
                               class="w-full px-3 py-2 border border-gray-300 !rounded-button focus:outline-none focus:border-primary"
                               required>
                    </div>
                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                        <input id="email" name="email" type="email"
                               class="w-full px-3 py-2 border border-gray-300 !rounded-button focus:outline-none focus:border-primary"
                               required>
                    </div>
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input id="password" name="password" type="password"
                               class="w-full px-3 py-2 border border-gray-300 !rounded-button focus:outline-none focus:border-primary"
                               required>
                    </div>
                    <div>
                        <label for="role" class="block text-sm font-medium text-gray-700 mb-1">角色</label>
                        <div class="relative">
                            <select id="role" name="role"
                                    class="w-full px-3 py-2 border border-gray-300 !rounded-button focus:outline-none focus:border-primary appearance-none bg-white"
                                    required>
                                <option value="user">user</option>
                                <option value="admin">admin</option>
                            </select>
                            <i class="fas fa-chevron-down absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end space-x-4 mt-6">
                    <button type="button" onclick="hideModal()"
                            class="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 !rounded-button whitespace-nowrap">
                        取消
                    </button>
                    <button type="button" onclick="submitUser()"
                            class="px-4 py-2 text-white bg-primary hover:bg-primary/90 !rounded-button whitespace-nowrap">
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    {{ super() }}
    <script>
        const page_num = document.getElementById('page_num').innerText;
        sessionStorage.setItem('userPage', page_num);

        function showModal(type, userId, username, email, role) {
            if (type === 'edit') {
                document.getElementById('userId').value = userId;
                document.getElementById('username').value = username;
                document.getElementById('email').value = email;
                document.getElementById("password").value = '';
                document.getElementById('role').value = role;
            }
            const modal = document.getElementById('userModal');
            const modalTitle = document.getElementById('modalTitle');
            modal.style.display = 'block';
            modalTitle.textContent = type === 'add' ? '添加用户' : '编辑用户';
        }

        function hideModal() {
            const user_form = document.getElementById('userForm');
            user_form.onreset;
            const modal = document.getElementById('userModal');
            modal.style.display = 'none';
        }

        function submitUser() {
            const modalTitle = document.getElementById('modalTitle');
            const username = document.getElementById("username").value;
            const email = document.getElementById("email").value;
            const password = document.getElementById("password").value;
            const role = document.getElementById("role").value;

            if (modalTitle.textContent === "添加用户") {
                fetch('/admin/add_user', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        username: username,
                        email: email,
                        password: password,
                        role: role
                    })
                }).then(() => {
                    window.location.href = `/admin/manage_users/${page_num}`;
                });
            } else if (modalTitle.textContent === "编辑用户") {
                const userId = document.getElementById("userId").value;
                fetch('/admin/edit_user', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        userId: userId,
                        username: username,
                        email: email,
                        password: password,
                        role: role
                    })
                }).then(() => {
                    window.location.href = `/admin/manage_users/${page_num}`;
                });
            }
        }

        function delete_user(userId) {
            // 显示确认弹窗
            showConfirm('是否确认删除?').then(confirmed => {
                if (confirmed) {
                    // 用户点击确认后执行删除操作
                    fetch(`/admin/delete_user/${userId}`).then(()=>{
                        window.location.href = `/admin/manage_users/${page_num}`;
                    })
                }
            });
        }
    </script>
{% endblock %}